<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增定向包')" />
    <style>
        .level1 {
            width: 200px;
            background: white;
            box-shadow: 0 0 0 1px rgba(211, 211, 211, 0.5);
            overflow-y: auto; /* 使得div可滚动 */
        }
        .level2 {
            width: 150px;
            background: white;
            box-shadow: 0 0 0 1px rgba(211, 211, 211, 0.5);
            overflow-y: auto; /* 使得div可滚动 */
        }
        .level1 div, .level2 div {
            padding: 3px 10px;
            cursor: pointer; /* 使得鼠标悬停时显示为指针 */
            display: flex; /* 使用flex布局 */
            align-items: center; /* 垂直居中 */
            justify-content: flex-start; /* 水平左对齐 */
        }
        #level3 div {
            line-height: 1.5; /* 使文字和复选框上下居中 */
            padding-left: 10px; /* 左边距 10px */
            background-color: #f7f8fc; /* 灰底 */
            border-radius: 5px; /* 圆角 */
            margin: 5px 5px 0 5px; /* 每个城市条目之间的间距 */
            display: flex; /* 使用flex布局 */
            align-items: center; /* 确保内容上下居中 */
        }
        .level3 {
            display: flex; /* 启用 Flexbox */
            font-weight: bold; /* 字体加粗 */
            padding-left: 10px; /* 左边距 10px */
            align-items: center; /* 确保内容上下居中 */
        }

        .odd {
            background-color: #f7f8fc; /* 隔行背景色 */
        }
        .even {
            background-color: #ffffff;
        }
        .selected {
            font-weight: bold; /* 选中时加粗 */
            color: blue; /* 选中时字体变蓝 */
        }
        .arrow {
            margin-left: auto; /* 将箭头推到右侧 */
            color: gray; /* 箭头颜色 */
            font-weight: bold; /* 箭头加粗 */
            align-self: center; /* 垂直居中 */
        }
        /* 添加复选框和标签的距离 */
        input[type="checkbox"] {
            margin-right: 8px; /* 设置复选框右边距 */
            vertical-align: middle; /* 确保复选框垂直居中 */
        }
    </style>
</head>
<body class="white-bg">

<form class="form-horizontal m-t" id="commentForm">
    <div class="form-group">
        <!--地区-->
        <div class="form-group">
            <label class="col-sm-2 control-label">区域定向：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="region1" name="regionRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="region2" name="regionRadio">设置</label>
            </div>
        </div>
        <div id="regionD">
            <div class="form-group">
                <div class="col-sm-2"></div>
                <div class="col-sm-9" style="display: flex; flex-direction: column;">
                    <div style="display: flex; align-items: stretch;">
                        <div style="height: 40px; width: 350px; background: white; box-shadow: 0 0 0 1px rgba(211, 211, 211, 0.5);">
                            <input type="text" placeholder="请输入地名" class="form-control" id="regionSou" style="border: red 0 solid;height: 100%;" />
                        </div>
                        <div class="level3" style="height: 40px; width: 150px;background: white; box-shadow: 0 0 0 1px rgba(211, 211, 211, 0.5);">
                            已选城市：<span id="selectedCityCount">0</span>/370
                        </div>
                    </div>
                    <div style="display: flex; align-items: stretch;">
                        <div style="display: flex; align-items: stretch;">
                            <div class="level1" id="level1" style="height: 200px;"></div>
                            <div class="level2" id="level2" style="height: 200px;"></div>
                            <div class="level2" id="level3" style="height: 200px;"></div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">是否常驻：</label>
                <div class="col-sm-9">
                    <label class="radio-box">
                        <input type="radio" value=1 checked="" id="stayType1" name="stayType">常驻</label>
                    <label class="radio-box">
                        <input type="radio" value=2 id="stayType2" name="stayType">当前</label>
                </div>
            </div>
        </div>
        <!--性别-->
        <div class="form-group">
            <label class="col-sm-2 control-label">用户性别：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="sex1" name="sexRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="sex2" name="sexRadio">设置</label>
            </div>
        </div>
        <div id="sexD" class="form-group">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-9">
                <label class="checkbox-inline">
                    <input type="checkbox" value="19" id="sexCheckbox19" name="sexList">男</label>

                <label class="checkbox-inline">
                    <input type="checkbox" value="20" id="sexCheckbox20" name="sexList">女</label>

            </div>
        </div>
        <!--年龄-->
        <div class="form-group">
            <label class="col-sm-2 control-label">用户年龄：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="age1" name="ageRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="age2" name="ageRadio">设置</label>
            </div>
        </div>
        <div id="ageD" class="form-group">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-9">
                <label class="checkbox-inline">
                    <input type="checkbox" value="25" id="ageCheckbox25" name="ageList">0-17岁</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="26" id="ageCheckbox26" name="ageList">18-24岁</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="27" id="ageCheckbox27" name="ageList">25-29岁</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="28" id="ageCheckbox28" name="ageList">30-39岁</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="29" id="ageCheckbox29" name="ageList">40-49岁</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="30" id="ageCheckbox30" name="ageList">50岁以上</label>
            </div>
        </div>
        <!--人群包 禁用-->
        <div class="form-group" style="display: none">
            <label class="col-sm-2 control-label">人群包：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="customRadio1" name="customRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="customRadio12" name="customRadio" disabled>设置</label>
            </div>
        </div>
        <!--安装行为-->
        <div class="form-group"  style="display: none">
            <label class="col-sm-2 control-label">安装行为：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="installBehaviorRadio1" name="installBehaviorRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="installBehaviorRadio2" name="installBehaviorRadio" disabled>设置</label>
            </div>
        </div>
        <!--启动行为-->
        <div class="form-group"  style="display: none">
            <label class="col-sm-2 control-label">安装行为：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="startBehaviorRadio1" name="startBehaviorRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="startBehaviorRadio2" name="startBehaviorRadio" disabled>设置</label>
            </div>
        </div>
        <!--兴趣行为-->
        <div class="form-group"  style="display: none">
            <label class="col-sm-2 control-label">兴趣行为：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="interestSetRadio1" name="interestSetRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="interestSetRadio2" name="interestSetRadio" disabled>设置</label>
            </div>
        </div>
        <!--网络环境-->
        <div class="form-group">
            <label class="col-sm-2 control-label">网络环境：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="network1" name="network">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="network2" name="network" >定向WIFI</label>
            </div>
        </div>
        <!--安卓版本-->
        <div class="form-group">
            <label class="col-sm-2 control-label">安卓版本：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="androidVersionSetRadio1" name="androidVersionSetRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="androidVersionSetRadio2" name="androidVersionSetRadio">设置</label>
            </div>
        </div>
        <div id="androidVersionSetD" class="form-group">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-9">
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650003" id="androidVersionSet1650003" name="androidVersionSet">安卓4及以下</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650004" id="androidVersionSet1650004" name="androidVersionSet">安卓5</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650005" id="androidVersionSet1650005" name="androidVersionSet">安卓6</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650006" id="androidVersionSet1650006" name="androidVersionSet">安卓7</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650007" id="androidVersionSet1650007" name="androidVersionSet">安卓8</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650008" id="androidVersionSet1650008" name="androidVersionSet">安卓9</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650001" id="androidVersionSet1650001" name="androidVersionSet">安卓10</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650002" id="androidVersionSet1650002" name="androidVersionSet">安卓11</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650009" id="androidVersionSet1650009" name="androidVersionSet">安卓12</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650010" id="androidVersionSet1650010" name="androidVersionSet">安卓13</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1650011" id="androidVersionSet1650011" name="androidVersionSet">安卓14</label>
            </div>
        </div>
        <!--购机价格-->
        <div class="form-group">
            <label class="col-sm-2 control-label">购机价格：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="phonePriceSetRadio1" name="phonePriceSetRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="phonePriceSetRadio2" name="phonePriceSetRadio" >设置</label>
            </div>
        </div>
        <div id="phonePriceSetD" class="form-group">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-9">
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530021" id="phonePriceSet1530021" name="phonePriceSet">4000~4500</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530020" id="phonePriceSet1530020" name="phonePriceSet">3500~4000</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530019" id="phonePriceSet1530019" name="phonePriceSet">3000~3500</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530018" id="phonePriceSet1530018" name="phonePriceSet">2500~3000</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530017" id="phonePriceSet1530017" name="phonePriceSet">2000~2500</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530016" id="phonePriceSet1530016" name="phonePriceSet">1500~2000</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530015" id="phonePriceSet1530015" name="phonePriceSet">1000~1500</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530014" id="phonePriceSet1530014" name="phonePriceSet">0~1000</label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530022" id="phonePriceSet1530022" name="phonePriceSet">>4500</label>
            </div>
        </div>
        <!--手机系列-->
        <div class="form-group">
            <label class="col-sm-2 control-label">手机系列：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="phoneSeriesSetRadio1" name="phoneSeriesSetRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="phoneSeriesSetRadio2" name="phoneSeriesSetRadio" >设置</label>
            </div>
        </div>
        <div id="phoneSeriesSetD" class="form-group">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-9">
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530002" id="phoneSeriesSet1530002" name="phoneSeriesSet">i系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530001" id="phoneSeriesSet1530001" name="phoneSeriesSet">E系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530003" id="phoneSeriesSet1530003" name="phoneSeriesSet">K系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530004" id="phoneSeriesSet1530004" name="phoneSeriesSet">NEX系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530005" id="phoneSeriesSet1530005" name="phoneSeriesSet">S系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530006" id="phoneSeriesSet1530006" name="phoneSeriesSet">V系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530007" id="phoneSeriesSet1530007" name="phoneSeriesSet">Y系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530008" id="phoneSeriesSet1530008" name="phoneSeriesSet">Z系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530009" id="phoneSeriesSet1530009" name="phoneSeriesSet">iQOO系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530010" id="phoneSeriesSet1530010" name="phoneSeriesSet">X系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530011" id="phoneSeriesSet1530011" name="phoneSeriesSet">Xplay系列
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1530012" id="phoneSeriesSet1530012" name="phoneSeriesSet">U系列
                </label>

            </div>
        </div>
        <!--运营商-->
        <div class="form-group">
            <label class="col-sm-2 control-label">运营商：</label>
            <div class="col-sm-9">
                <label class="radio-box">
                    <input type="radio" value="1" checked="" id="networkOperatorSetRadio1" name="networkOperatorSetRadio">不限</label>
                <label class="radio-box">
                    <input type="radio" value="2" id="networkOperatorSetRadio2" name="networkOperatorSetRadio" >设置</label>
            </div>
        </div>
        <div id="networkOperatorSetD" class="form-group">
            <label class="col-sm-2 control-label"></label>
            <div class="col-sm-9">
                <label class="checkbox-inline">
                    <input type="checkbox" value="1580101" id="networkOperatorSet1580101" name="networkOperatorSet">中国移动
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1580104" id="networkOperatorSet1580104" name="networkOperatorSet">中国联通
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1580107" id="networkOperatorSet1580107" name="networkOperatorSet">中国电信
                </label>
                <label class="checkbox-inline">
                    <input type="checkbox" value="1580110" id="networkOperatorSet1580110" name="networkOperatorSet">其他
                </label>
            </div>
        </div>
        <!--定向包名称-->
        <div class="form-group">
            <label class="col-sm-2 control-label">定向包名称：</label>
            <div class="col-sm-4">
                <input type="text" id="name" name="name" class="form-control" placeholder="请输入定向包名称，200个字符以内">
            </div>
        </div>
        <!--备注说明-->
        <div class="form-group">
            <label class="col-sm-2 control-label">备注：</label>
            <div class="col-sm-4">
                <textarea type="text" rows="5"  id="remark" name="remark" class="form-control" placeholder="请输入备注文本"></textarea>
            </div>
        </div>

    </div>
</form>



<th:block th:include="include :: footer" />
<script src="../static/js/audience.json" th:src="@{/js/audience.json}"></script>
<!-- 行政区多选组件 -->
<script th:inline="javascript">
    var regionList = [];
    var data = jsonData.region;
    const level1Div = $('#level1');
    const level2Div = $('#level2');
    const level3Div = $('#level3');
    $.each(data, function (index, item) {
        const div = $('<div></div>');
        const checkbox = $('<input type="checkbox" />').attr('id', 'level1-checkbox-' + item.tagId).on('click', function (e) {
            handleParentCheckboxClick(item, $(this).is(':checked'));
        });
        div.append(checkbox);
        const label = $('<label style="margin-bottom: 0px;padding-top: 5px;"></label>').text(item.tagName);
        div.append(label);
        // 如果有子集，添加箭头
        if (item.childBaseTag && item.childBaseTag.length > 0) {
            div.append($('<span class="arrow">></span>'));
        }
        div.addClass(index % 2 === 0 ? 'even' : 'odd');
        div.on('click', function () {
            // 展开下拉，显示子集
            showChildren(item, checkbox);
        });
        level1Div.append(div);
    });

    function renderCheckboxes() {
        // 清空容器
        level1Div.empty();
        level2Div.empty();
        level3Div.empty();

        $.each(data, function (index, item) {
            const div = $('<div></div>');
            const checkbox = $('<input type="checkbox" />').attr('id', 'level1-checkbox-' + item.tagId).on('click', function (e) {
                handleParentCheckboxClick(item, $(this).is(':checked'));
            });
            div.append(checkbox);
            const label = $('<label style="margin-bottom: 0px;padding-top: 5px;"></label>').text(item.tagName);
            div.append(label);
            // 如果有子集，添加箭头
            if (item.childBaseTag && item.childBaseTag.length > 0) {
                div.append($('<span class="arrow">></span>'));
            }
            div.addClass(index % 2 === 0 ? 'even' : 'odd');
            div.on('click', function () {
                // 展开下拉，显示子集
                showChildren(item, checkbox);
            });
            level1Div.append(div);
        });
    }


    // 监听输入框变化事件
    $('#regionSou').on('input', function() {
        var searchTerm = $(this).val().trim().toLowerCase(); // 获取输入值并转换为小写
        if (searchTerm === "") {
            return; // 如果输入为空，则不处理
        }
        // 遍历 level1 的每个 div，查找包含搜索词的项目
        $('#level1 div').each(function() {
            var text = $(this).text().toLowerCase(); // 获取 div 的文本内容并转换为小写
            if (text.includes(searchTerm)) {
                // 找到包含搜索词的 div，滚动到该元素
                $('#level1').scrollTop($(this).position().top + $('#level1').scrollTop()  -45);
                return false; // 找到第一个匹配的项后，停止遍历
            }
        });
    });
    function showChildren(item, checkbox) {
        level2Div.empty();
        if (item.childBaseTag) {
            $.each(item.childBaseTag, function (index, childItem) {
                const div = $('<div></div>');
                const childCheckbox = $('<input type="checkbox" />')
                    .attr('id', 'level2-checkbox-' + childItem.tagId)
                    .on('click', function () {
                        handleChildCheckboxClick(childItem.tagId, $(this).is(':checked'), item, checkbox);
                    });
                // 根据 regionList 恢复子级的选中状态
                if (regionList.includes(childItem.tagId)) {
                    childCheckbox.prop('checked', true);
                }
                div.append(childCheckbox);
                const label = $('<label style="margin-bottom: 0px;padding-top: 5px;"></label>')
                    .attr('for', childCheckbox.attr('id'))
                    .text(childItem.tagName);
                div.append(label);
                div.addClass(index % 2 === 0 ? 'even' : 'odd');
                level2Div.append(div);
            });
            // 根据子集的勾选情况更新父级复选框
            updateParentCheckbox(checkbox, item.childBaseTag);
        }
    }
    function handleChildCheckboxClick(tagId, isChecked, parentItem, parentCheckbox) {
        if (isChecked) {
            regionList.push(tagId);
        } else {
            regionList = regionList.filter(id => id !== tagId);
        }
        // 每次子级复选框被点击后，立即更新父级复选框的状态
        updateParentCheckbox(parentCheckbox, parentItem.childBaseTag);
        // 更新已选城市显示
        updateSelectedCityDisplay();
        console.log('当前 regionList: ', regionList);
    }

    function handleParentCheckboxClick(item, isChecked) {
        if (isChecked) {
            // 如果勾选父级，则勾选所有子级
            if (item.childBaseTag && item.childBaseTag.length > 0) {
                item.childBaseTag.forEach(childItem => {
                    if (!regionList.includes(childItem.tagId)) {
                        regionList.push(childItem.tagId);
                    }
                });
            } else {
                // 没有子级，勾选父级
                if (!regionList.includes(item.tagId)) {
                    regionList.push(item.tagId);
                }
            }
        } else {
            // 如果取消父级，则取消所有子级的勾选
            if (item.childBaseTag && item.childBaseTag.length > 0) {
                item.childBaseTag.forEach(childItem => {
                    regionList = regionList.filter(id => id !== childItem.tagId);
                });
            } else {
                regionList = regionList.filter(id => id !== item.tagId);
            }
        }

        // 更新已选城市显示
        updateSelectedCityDisplay();

        console.log('当前 regionList: ', regionList);
    }

    function updateParentCheckbox(checkbox, childItems) {
        let allChecked = true;
        let anyChecked = false;
        childItems.forEach(childItem => {
            if (regionList.includes(childItem.tagId)) {
                anyChecked = true;
            } else {
                allChecked = false;
            }
        });

        if (allChecked) {
            checkbox.prop('checked', true).prop('indeterminate', false);
        } else if (anyChecked) {
            checkbox.prop('checked', false).prop('indeterminate', true);
        } else {
            checkbox.prop('checked', false).prop('indeterminate', false);
        }
    }

    function updateSelectedCityDisplay() {
        // 更新计数
        $('#selectedCityCount').text(regionList.length);

        // 获取已选城市的名称
        const selectedCities = [];
        jsonData.region.forEach(function (item) {
            // 如果父级被选中
            if (regionList.includes(item.tagId)) {
                selectedCities.push(item.tagName);
            }
            // 如果子级被选中
            if (item.childBaseTag) {
                item.childBaseTag.forEach(function (childItem) {
                    if (regionList.includes(childItem.tagId)) {
                        selectedCities.push(childItem.tagName);
                    }
                });
            }
        });

        // 清空并更新已选城市列表
        const selectedCityDiv = $('#level3');
        selectedCityDiv.empty(); // 清空之前的城市列表
        selectedCities.forEach(function (city) {
            const cityDiv = $('<div></div>').text(city);
            selectedCityDiv.append(cityDiv);
        });
    }

    $(document).ready(function() {
        updateSelectedCityDisplay(); // 初始化时更新已选城市显示
    });

</script>

<!-- 其他组件 -->
<script th:inline="javascript">
    $(document).ready(function() {
        $('#regionD').hide();
        $('#sexD').hide();
        $('#ageD').hide();
        $('#androidVersionSetD').hide();
        $('#phonePriceSetD').hide();
        $('#phoneSeriesSetD').hide();
        $('#networkOperatorSetD').hide();

        $('input[name="regionRadio"]').change(function (){
            var regionRadioC = $('input[name="regionRadio"]:checked').val();
            if (regionRadioC==="1"){
                $('#regionD').hide();
                regionList = [];
                renderCheckboxes();
            }else if(regionRadioC==="2"){
                $('#regionD').show();
            }
        });

        $('input[name="sexRadio"]').change(function (){
            var sexD = $('input[name="sexRadio"]:checked').val();
            if (sexD==="1"){
                $('input[name="sexList"]').prop('checked', false);
                $('#sexD').hide();
            }else if(sexD==="2"){
                $('#sexD').show();
            }
        });

        $('input[name="ageRadio"]').change(function (){
            var ageRadio = $('input[name="ageRadio"]:checked').val();
            if (ageRadio==="1"){
                $('input[name="ageList"]').prop('checked', false);
                $('#ageD').hide();
            }else if(ageRadio==="2"){
                $('#ageD').show();
            }
        });

        $('input[name="androidVersionSetRadio"]').change(function (){
            var androidVersionSetRadio = $('input[name="androidVersionSetRadio"]:checked').val();
            if (androidVersionSetRadio==="1"){
                $('input[name="androidVersionSet"]').prop('checked', false);
                $('#androidVersionSetD').hide();
            }else if(androidVersionSetRadio==="2"){
                $('#androidVersionSetD').show();
            }
        });

        $('input[name="phonePriceSetRadio"]').change(function (){
            var phonePriceSetRadio = $('input[name="phonePriceSetRadio"]:checked').val();
            if (phonePriceSetRadio==="1"){
                $('input[name="phonePriceSet"]').prop('checked', false);
                $('#phonePriceSetD').hide();
            }else if(phonePriceSetRadio==="2"){
                $('#phonePriceSetD').show();
            }
        });

        $('input[name="phoneSeriesSetRadio"]').change(function (){
            var phoneSeriesSetRadio = $('input[name="phoneSeriesSetRadio"]:checked').val();
            if (phoneSeriesSetRadio==="1"){
                $('input[name="phoneSeriesSet"]').prop('checked', false);
                $('#phoneSeriesSetD').hide();
            }else if(phoneSeriesSetRadio==="2"){
                $('#phoneSeriesSetD').show();
            }
        });

        $('input[name="networkOperatorSetRadio"]').change(function (){
            var networkOperatorSetRadio = $('input[name="networkOperatorSetRadio"]:checked').val();
            if (networkOperatorSetRadio==="1"){
                $('input[name="networkOperatorSet"]').prop('checked', false);
                $('#networkOperatorSetD').hide();
            }else if(networkOperatorSetRadio==="2"){
                $('#networkOperatorSetD').show();
            }
        });
    });
</script>
<!-- 保存定向包 -->
<script th:inline="javascript">
    // 根据 ID 添加点击事件
    $('#submitButton').on('click', audienceInfoAdd);
    var audienceInfo = {
        sexList: [],
        networkOperatorSet: [],
        androidVersionSet: [],
        installedApp: 1,
        phoneSeriesSet: [],
        region: {
            stayType: null,
            regionCodeList: []
        },
        phonePriceSet: [],
        ageList: [],
        network: 1
    };

    function audienceInfoAdd(){
        if(regionList.length>0){
            audienceInfo.region.regionCodeList = regionList;
            audienceInfo.region.stayType =Number($('input[name="stayType"]:checked').val());
        }
        audienceInfo.sexList=$('input[name="sexList"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.ageList=$('input[name="ageList"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.network=Number($('input[name="network"]:checked').val())
        audienceInfo.androidVersionSet=$('input[name="androidVersionSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.phonePriceSet=$('input[name="phonePriceSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.phoneSeriesSet=$('input[name="phoneSeriesSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.networkOperatorSet=$('input[name="networkOperatorSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();

        // 构建表单数据
        const formData = new FormData();
        formData.append('name', $('#name').val());  // 添加 name 字段
        formData.append('audienceInfo', JSON.stringify(audienceInfo));  // 添加 audienceInfo 字段（序列化为字符串）
        formData.append('remark', $('#remark').val());  // 添加 remark 字段（如果需要）


        // 发送 AJAX 请求
        // $.ajax({
        //     url: '/system/audienceinfo/add',
        //     type: 'POST',
        //     processData: false,  // 不处理数据
        //     contentType: false,  // 不设置内容类型，使用 FormData 的内容类型
        //     data: formData,  // 发送表单数据
        //     success: function(response) {
        //         console.log('Success:', response);  // 请求成功后的处理
        //         if (response.code == 0) {
        //             $.modal.msgSuccess(response.msg);
        //         } else {
        //             $.modal.msgWarning(response.msg);
        //         }
        //     },
        //     error: function(xhr, status, error) {
        //         console.error('Error:', error);  // 请求失败后的处理
        //         $.modal.msgWarning(error);
        //     }
        // });
    }

    var vivoAudienceinfo = [[${vivoAudienceinfo}]];

    $(document).ready(function () {
        $('#name').val(vivoAudienceinfo.name);
        $('#remark').val(vivoAudienceinfo.remark);
        var audienceInfoB = JSON.parse(vivoAudienceinfo.audienceInfo);
        console.log(audienceInfoB);

        // 区域定向回显
        if (audienceInfoB.region && audienceInfoB.region.stayType != null) {
            // 单选按钮更新
            if(audienceInfoB.region.stayType ===1){
                $('#stayType1').click();
                $('#stayType2').closest('div').removeClass('checked');
                $('#stayType1').closest('div').addClass('checked');
            }else{
                $('#stayType2').click();
                $('#stayType1').closest('div').removeClass('checked');
                $('#stayType2').closest('div').addClass('checked');
            }

            if (audienceInfoB.region.regionCodeList && audienceInfoB.region.regionCodeList.length > 0) {
                // 单选按钮更新
                $('#region2').click();
                $('#region1').closest('div').removeClass('checked');
                $('#region2').closest('div').addClass('checked');

                audienceInfoB.region.regionCodeList.forEach(regionCode => {
                    regionList.push(regionCode); // 将 regionCode 添加到 regionList

                    // 选中对应的 checkbox
                    const level1Checkbox = $('#level1-checkbox-' + regionCode);
                    if (level1Checkbox.length > 0) {
                        level1Checkbox.prop('checked', true);

                        // 处理直辖市和普通省份
                        const selectedProvince = data.find(item => item.tagId === regionCode);
                        if (selectedProvince) {
                            if (!selectedProvince.childBaseTag) {
                                // 直辖市，直接更新显示
                            } else {
                                // 省份，展开子级菜单并触发点击事件
                                showChildren(selectedProvince, level1Checkbox);
                                level1Checkbox.trigger('click'); //这行代码很关键，用来更新父级选中状态
                            }
                        }
                    } else { //处理二级地区
                        const level2Checkbox = $('#level2-checkbox-' + regionCode);
                        if (level2Checkbox.length > 0) {
                            level2Checkbox.prop('checked', true);
                            level2Checkbox.trigger('click');
                        }
                    }
                });
                // 在循环结束后，统一更新父级 checkbox 的状态和已选城市显示
                audienceInfoB.region.regionCodeList.forEach(regionCode => {
                    const selectedCity = data.find(province => province.childBaseTag && province.childBaseTag.some(city => city.tagId === regionCode));
                    if(selectedCity){
                        const parentCheckbox = $('#level1-checkbox-' + selectedCity.tagId);
                        updateParentCheckbox(parentCheckbox, selectedCity.childBaseTag);
                    }
                });
                updateSelectedCityDisplay(); // 更新已选城市显示
            }
        }

        // 性别回显
        if (audienceInfoB.sexList && audienceInfoB.sexList.length > 0) {
            $('#sex2').click(); // 点击“设置”按钮
            $('#sex1').closest('div').removeClass('checked');
            $('#sex2').closest('div').addClass('checked');
            audienceInfoB.sexList.forEach(sex => {
                $('#sexCheckbox' + sex).prop('checked', true);
            });
        }

        // 年龄回显，逻辑与性别类似
        if (audienceInfoB.ageList && audienceInfoB.ageList.length > 0) {
            $('#age2').click();
            $('#age1').closest('div').removeClass('checked');
            $('#age2').closest('div').addClass('checked');
            audienceInfoB.ageList.forEach(age => {
                $('#ageCheckbox' + age).prop('checked', true);

            });
        }

        // 网络环境回显
        if(audienceInfoB.network===2){
            $('#network2').click();
            $('#network1').closest('div').removeClass('checked');
            $('#network2').closest('div').addClass('checked');
        }

        // androidVersionSet 回显
        if (audienceInfoB.androidVersionSet && audienceInfoB.androidVersionSet.length > 0) {
            $('#androidVersionSetRadio2').click();
            $('#androidVersionSetRadio1').closest('div').removeClass('checked');
            $('#androidVersionSetRadio2').closest('div').addClass('checked');
            audienceInfoB.androidVersionSet.forEach(version => {
                $('#androidVersionSet' + version).prop('checked', true);
            });
        }

        // phonePriceSet 回显
        if (audienceInfoB.phonePriceSet && audienceInfoB.phonePriceSet.length > 0) {
            $('#phonePriceSetRadio2').click();
            $('#phonePriceSetRadio1').closest('div').removeClass('checked');
            $('#phonePriceSetRadio2').closest('div').addClass('checked');
            audienceInfoB.phonePriceSet.forEach(price => {
                $('#phonePriceSet' + price).prop('checked', true);
            });
        }
        // phoneSeriesSet 回显
        if (audienceInfoB.phoneSeriesSet && audienceInfoB.phoneSeriesSet.length > 0) {
            $('#phoneSeriesSetRadio2').click();
            $('#phoneSeriesSetRadio1').closest('div').removeClass('checked');
            $('#phoneSeriesSetRadio2').closest('div').addClass('checked');
            audienceInfoB.phoneSeriesSet.forEach(series => {
                $('#phoneSeriesSet' + series).prop('checked', true);
            });
        }

        // networkOperatorSet 回显
        if (audienceInfoB.networkOperatorSet && audienceInfoB.networkOperatorSet.length > 0) {
            $('#networkOperatorSetRadio2').click();
            $('#networkOperatorSetRadio1').closest('div').removeClass('checked');
            $('#networkOperatorSetRadio2').closest('div').addClass('checked');
            audienceInfoB.networkOperatorSet.forEach(operator => {
                $('#networkOperatorSet' + operator).prop('checked', true);
            });
        }
    });
    var prefix = ctx + "system/audienceinfo";
    function submitHandler() {
        if(regionList.length>0){
            audienceInfo.region.regionCodeList = regionList;
            audienceInfo.region.stayType =Number($('input[name="stayType"]:checked').val());
        }
        audienceInfo.sexList=$('input[name="sexList"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.ageList=$('input[name="ageList"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.network=Number($('input[name="network"]:checked').val())
        audienceInfo.androidVersionSet=$('input[name="androidVersionSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.phonePriceSet=$('input[name="phonePriceSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.phoneSeriesSet=$('input[name="phoneSeriesSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        audienceInfo.networkOperatorSet=$('input[name="networkOperatorSet"]:checked').map(function() {
            return Number($(this).val());
        }).get();
        vivoAudienceinfo.audienceInfo= JSON.stringify(audienceInfo);

        vivoAudienceinfo.name = $('#name').val();
        vivoAudienceinfo.remark = $('#remark').val();

        $.operate.save(prefix + "/edit",vivoAudienceinfo );
    }
</script>
</body>
</html>
